package top.conangao.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

/**
 * @author ConanGao
 * @description SpringUtils
 * @since 1.0
 **/
public class SpringUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName){
        checkForInitialized();
        return (T) applicationContext.getBean(beanName);
    }
    
    public static <T> T getBeanByClass(Class<T> clazz){
        checkForInitialized();
        return (T)applicationContext.getBean(clazz);
    }

    public static <T> Map<String, T> getBeansByClass(Class<T> clazz) {
        checkForInitialized();
        return applicationContext.getBeansOfType(clazz);
    }

    private static void checkForInitialized() {
        if (applicationContext == null) {
            synchronized (SpringUtils.class) {
                if (applicationContext == null) {
                    try {
                        SpringUtils.class.wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }
    }
}
